package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Product;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.Page;
import com.kaishengit.util.RowMapper;

public class ProductDao {

	private DBHelp<Product> db = new DBHelp<Product>();
	
	public List<Product> findAll() {
		String sql = "select id,prodname,price from t_prod";
		return db.executeQueryForList(sql, new ProductRowMapper());
	}
	
	public Page<Product> findByPage(Page<Product> page) {
		String sql = "select id,prodname,price from t_prod limit ?,?";
		List<Product> list =  db.executeQueryForList(sql, new ProductRowMapper(),page.getStartNum(),page.getPageSize());
		page.setResult(list);
		return page;
	}
	
	public void save(String proName,float price) {
		System.out.println("dao de save");
		String sql = "insert into t_prod(prodname,price) values(?,?)";
		db.executeSQL(sql, proName,price);
		
	}
	
	public void del(int id) {
		String sql = "delete from t_prod where id = ?";
		System.out.println(sql);
		db.executeSQL(sql, id);
	}
	
	public void update(Product pro) {
		String sql = "update t_prod set prodname=?,price=? where id = ?";
		db.executeSQL(sql, pro.getProdname(),pro.getPrice(),pro.getId());
	}
	
	public Product findById(int id) {
		String sql = "select id,prodname,price from t_prod where id = ?";
		return db.executeQueryForObject(sql, new ProductRowMapper(), id);
	}
	
	public int getTotalNums() {
		String sql = "select count(*) from t_prod";
		return db.executeQueryForCount(sql);
	}
	
	
	private class ProductRowMapper implements RowMapper<Product> {

		public Product mapperRow(ResultSet rs) throws SQLException {
			Product p = new Product();
			p.setId(rs.getInt("id"));
			p.setPrice(rs.getFloat("price"));
			p.setProdname(rs.getString("prodname"));
			return p;
		}
		
	}
}
